package servlet;

import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/blog_detail")
public class BlogDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");


        User user=Util.checkLogin(req);
        if(user==null){
            System.out.println("当前未登录无法访问博客详情页！");
            resp.sendRedirect("blog_login.html");
            return;
        }


        String blogId=req.getParameter("blogId");
        if(blogId==null||blogId.equals("")){
            String html="<h3>blogId 为空!<h3>";
            resp.getWriter().write(html);
            return;
        }


        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectOne(Integer.parseInt(blogId));
        if(blog==null){
            String html="<h3>指定的博客不存在!<h3>";
            resp.getWriter().write(html);
            return;
        }

        UserDao userDao=new UserDao();
        User author=userDao.selectById(blog.getUserId());
        if(author==null){
            String html="<h3>指定的博客作者不存在!<h3>";
            resp.getWriter().write(html);
            return;
        }



        ServletContext context=getServletContext();
        TemplateEngine engine=(TemplateEngine) context.getAttribute("engine");
        WebContext webContext=new WebContext(req,resp,context);
        webContext.setVariable("blog",blog);
        webContext.setVariable("user",author);
        webContext.setVariable("showDeleteButton",user.getUserId()==author.getUserId());
        engine.process("blog_detail",webContext,resp.getWriter());
    }
}
